<?php
global $Config;
require_once($Config->WebCMSRoot.'Base/Control.php');
require_once($Config->WebCMSRoot.'Models/User.php');
require_once($Config->WebCMSRoot.'Views/User.php');

Class User extends BaseControl
{
	var $user;
	var $view;
	
	function User($parameters, &$page)
	{
		$this->user = new UserModel();
		$this->view = new UserView();
		
		parent::BaseControl($parameters, &$page);
	}

	function Execute()
	{
		$action = $this->GetParameter('action');
		if (empty($action))
		{
			$action = 'login';
		}
		
		switch ($action)
		{
			case 'login':
			case 'profile':
				if (isset($_POST['formID']))
				{
					if ($_POST['formID'] == sha1(session_id()) && isset($_POST['loginEmail']) && isset($_POST['loginPassword']))
					{
						// Login with credentials
						$this->parameters['email'][0] = $_POST['loginEmail'];
						$this->parameters['password'][0] = $_POST['loginPassword'];
						$this->user->Retrieve(&$this->parameters);
						
						if (count($this->user->Collection) == 1 && $this->user->Collection[0]->ID > 0)
						{
							$_SESSION['user'] = serialize($this->user->Collection[0]);
							$this->view = new UserView(); // re-init the view to pickup user in session
							$this->view->ShowProfile(&$this->user->Collection[0], true);
						}
						else
						{
							$this->view->ShowLoginForm(&$this->user->Collection[0], 'foutieve e-mail en/of paswoord.');
							// login error (wrong email/password)
						}
					}
				//$this->view->ShowContent(&$this->content->Collection[0]);
				}
				else
				{
					if (isset($_SESSION['user']))
					{
						$user = unserialize($_SESSION['user']);
						$this->parameters['id'][0] = $user->ID;
						$this->user->Retrieve(&$this->parameters);

						$this->view->ShowProfile(&$this->user->Collection[0]);
					}
					else
					{
						if ($action == 'login')
						{
							// No credentials: show login form
							$this->view->ShowLoginForm(&$this->user->Collection[0]);
						}
					}
				}
				break;
				
			case 'logout':
				$this->user = null;
				$_SESSION['user'] = null;
				unset($_SESSION['user']);
				$this->view->ShowLoginLink();
				break;
		}

		parent::Execute();
	}

	function ValidateArguments($args)
	{
		$valid = (count($args) >= 1);
		$valid = isset($args['action']);

		return $valid;
	}
}
?>